package com.qingzhu.service.impl;

import com.qingzhu.dao.AreasDao;
import com.qingzhu.dao.CitiesDao;
import com.qingzhu.dao.ProvincesDao;
import com.qingzhu.dao.impl.AreasDaoImpl;
import com.qingzhu.dao.impl.CitiesDaoImpl;
import com.qingzhu.dao.impl.ProvincesDaoImpl;
import com.qingzhu.pojo.Address;
import com.qingzhu.pojo.Areas;
import com.qingzhu.pojo.Cities;
import com.qingzhu.pojo.Provinces;
import com.qingzhu.service.AddressService;
import com.qingzhu.util.ListTypeHandler;

import java.util.List;

public class AddressServiceImpl implements AddressService {
    ProvincesDao provincesDao = new ProvincesDaoImpl();
    CitiesDao citiesDao = new CitiesDaoImpl();
    AreasDao areasDao = new AreasDaoImpl();

    @Override
    public List<Provinces> findProvinces() {
        return provincesDao.findProvinces();
    }

    @Override
    public List<Cities> findByProvincesId(String provincesId) {
        return citiesDao.findByProvincesId(provincesId);
    }

    @Override
    public List<Areas> findByCitiesId(String citiesId) {
        return areasDao.findByCitiesId(citiesId);
    }

    @Override
    public Address findReceivingAddress(String provinceId, String cityId, String areaId) {
        Provinces provinces = provincesDao.findProvincesById(provinceId);
        Cities cities = citiesDao.findCitiesById(cityId);
        Areas areas = areasDao.findAreasById(areaId);
        Address address = new Address();
        address.setProvinces(provinces);
        address.setCities(cities);
        address.setAreas(areas);
        return address;
    }

    @Override
    public Address findDefaultAddress(String addressUrl) {
        Address address = new Address();
        // 将字符串类型的关联地址转换成集合
        List<String> cityList = new ListTypeHandler<>().stringToList(addressUrl);
        // 优化获取省市区的代码
        cityList.stream().filter(c -> {
            Provinces provinces = provincesDao.findProvincesById(c);
            if (provinces!=null){address.setProvinces(provinces);}
            return provinces==null;
        }).filter(c -> {
            Cities cities = citiesDao.findCitiesById(c);
            if (cities!=null){address.setCities(cities);}
            return cities==null;
        }).filter(c -> {
            Areas areas = areasDao.findAreasById(c);
            if (areas!=null){address.setAreas(areas);}
            return areas==null;
        }).count();
        return address;
    }
}
